package com.yuanzheng.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author yuanzheng
 * @date 2020/4/14-22:03
 */
@Controller
public class MyController {

    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "Hell Shiro!");
        return "index";
    }

    @RequestMapping("/user/add")
    public String toAdd(Model model) {
        model.addAttribute("msg", "Hell Shiro Add!");
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String toUpdate(Model model) {
        model.addAttribute("msg", "Hell Shiro Update!");
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(Model model) {
        model.addAttribute("msg", "Hell Shiro Login!");
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model) {
        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();
        // 封装用户登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 实现登录
        try {
            subject.login(token);
            // 执行了登录操作
            model.addAttribute("msg", "Login Successfully!");

            Session session = subject.getSession();
            session.setAttribute("loginUser", subject);

            return "index";
        } catch (UnknownAccountException uae) {
            model.addAttribute("msg", "There is no user with username of " + token.getPrincipal());
            return "login";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg", "Password for account " + token.getPrincipal() + " was incorrect!");
            return "login";
        } catch (LockedAccountException lae) {
            model.addAttribute("msg", "The account for username " + token.getPrincipal() + " is locked.  " +
                    "Please contact your administrator to unlock it.");
            return "login";
        }
    }

    @RequestMapping("/toUnauPage")
    @ResponseBody
    public String toUnauPage() {
        return "You're not have authorize !!!";
    }

}
